package com.ys.util;

import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

public class TokenUtil {
	public static String ADMIN_TOKEN = "admin_token";
	
	public static String USER_TOKEN = "user_token";

    public static Long getAdminId(HttpServletRequest request) {
    	String tokenflag = ADMIN_TOKEN;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(tokenflag)) {
                    String value = cookie.getValue();
                    if (!StringUtils.isEmpty(value)) {
                        String id = value.substring(value.lastIndexOf("_") + 1, value.length());
                        return Long.valueOf(id);
                    }
                }
            }
        }
        return 0L;
    }

    public static Long getUserId(HttpServletRequest request) {
    	String tokenflag = USER_TOKEN;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(tokenflag)) {
                    String value = cookie.getValue();
                    if (!StringUtils.isEmpty(value)) {
                        String id = value.substring(value.lastIndexOf("_") + 1, value.length());
                        return Long.valueOf(id);
                    }
                }
            }
        }
        return null;
    }
}
